package com.zjs.io;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class GetPathDemo {
    public static void main(String[] args) {
        new GetPathDemo().getUrlByIO();
        new GetPathDemo().getUrlBySpringBoot();
    }
    //Java IO获取URL的方式
    public void getUrlByIO(){
        File file = null;
        String path = null;
        try {
            System.out.println();
            System.out.println("通过IO的方式获取URL：");
            //获取项目根目录
            //第一种方式
            path = System.getProperty("user.dir");
            System.out.println(path);
            //第二种方式
            file =new File("");
            path = file.getCanonicalPath();
            System.out.println(path);

            //获取类加载的根路径
            path = this.getClass().getResource("/").getPath();
            System.out.println(path);

            //获取当前类所在的路径
            path = this.getClass().getResource("").getPath();
            System.out.println(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void getUrlBySpringBoot(){
        File file = null;
        String path = null;
        try {
            System.out.println();
            System.out.println("通过SpringBoot的方式获取URL：");
            //获取项目根目录
            path = ResourceUtils.getURL("").getPath();
            System.out.println(path);

            //获取classes目录绝对路径
            path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            System.out.println(path);
            path = ResourceUtils.getURL("classpath:").getPath();
            System.out.println(path);

            //获取Resource下的资源
            //第一种方式
            path = ResourceUtils.getURL("java-learning/build/resources/main/static/a.html").getPath();
            System.out.println(path);
            //第二种方式
            path = new ClassPathResource("static/a.html").getURL().getPath();
            System.out.println(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
